package com.hyhy.hycloud.uaa.service;

import com.hyhy.hycloud.commons.util.misc.IdGenerator;
import com.hyhy.hycloud.uaa.exception.BadRequestSignatureException;
import com.hyhy.hycloud.uaa.security.crypto.Md5PasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 请求签名服务
 *
 * @author Xuegui Yuan
 * @date 2018-11-28
 */
@Service
public class RequestSignatureService {

    private PasswordEncoder signatureEncoder = new Md5PasswordEncoder();

    /**
     * 生成请求ID
     *
     * @return 请求ID
     */
    public String genRequestId() {
        return IdGenerator.uuid2();
    }

    /**
     * 计算签名
     *
     * @param bizCode   业务代码
     * @param requestId 请求ID
     * @return 签名
     */
    public String genSignature(String bizCode, String requestId) {
        String source = buildSource(bizCode, requestId);
        return signatureEncoder.encode(source);
    }

    /**
     * 验证签名
     *
     * @param requestId 请求ID
     * @param signature 签名
     * @throws BadRequestSignatureException 错误的请求签名
     */
    public void checkSignature(String bizCode, String requestId, String signature) throws BadRequestSignatureException {
        String source = buildSource(bizCode, requestId);
        if (!signatureEncoder.matches(source, signature)) {
            throw new BadRequestSignatureException();
        }
    }

    private String buildSource(String bizCode, String requestId) {
        return bizCode + requestId + LocalDateTime.now().getHour();
    }
}
